package cn.itsource.user.service.impl;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.LoginData;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.HttpUtil;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.domain.Permission;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.mapper.PermissionMapper;
import cn.itsource.user.constant.WxConstants;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.Wxuser;
import cn.itsource.user.dto.LoginDto;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.mapper.WxuserMapper;
import cn.itsource.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.通过account和type去查数据库 - Logininfo对象
        Logininfo logininfo =  logininfoMapper.accountLogin(loginDto);
        //2.判断Logininfo对象为null - 账号错误 - 抛异常
        if(logininfo == null){
            throw new BusinessException("用户名错误");
        }else{
            //3.不为null - 判断密码（将md5（密码+盐值） 和  Logininfo对象的密码进行对象）
            String inputPwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if(!inputPwd.equals(logininfo.getPassword())){
                //3.1.密码失败  - 抛异常
                throw new BusinessException("密码错误");
            }else{

                //登陆成功，Jwt操作
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);

                /*//3.2.成功 - 登录成功 - 生成token(uuid)  - 保存到redis - 30分钟
                String token = UUID.randomUUID().toString();
                //保存到redis的数据必须实现序列化
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

                //4.将token和登录信息对象对存在Map ，然后返回
                Map<String, Object> map = new HashMap<>();
                map.put("token",token); //后续做登录拦截验证
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo); //让前端显示用户信息*/

                return map;
            }
        }
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("logininfo",logininfo);
        //封装成一个LoginData对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);

        if(logininfo.getType()==0){//管理员
            //1.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有菜单
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId()); //查询当前登录人的所有二级菜单以及所属的一级菜单
            //2.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
            map.put("menus",menus);
            map.put("permissions",permissions);
        }

        try {
            //3.获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //4.通过私钥对LoginData对象进行加密，加密成jwt字符串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);

            //5.将以上四个信息：logininfo，所有菜单，所有权限，jwtToken都要封装到Map进行返回 - 最终返回给前端
            //a.logininfo 返回给前端 - 回显信息
            //b.jwtToken 返回给前端 - 登陆权限
            //c.所有菜单  返回给前端 - 动态路由 - 实现动态菜单
            //d.所有权限  返回给前端 - 资源权限
            //疑问：jwtToken有这三个信息，但是需要解密 - but我们的前端没有解码。所以才要将logininfo，所有菜单，所有权限传递给前端
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;

        //最终通过controller接口将map响应给前端：前台用户logininfo + token，后台管理员：4个
    }

   @Override
    public AjaxResult wechatLogin(String code) {
        //1.准备请求和替换参数
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE",code);
        //2.使用HttpUtil发送请求
        String jsonStr = HttpUtil.httpGet(url);
        /*
        * {
            "access_token":"ACCESS_TOKEN",
            "expires_in":7200,
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID",
            "scope":"SCOPE",
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
        * */
        //3.对返回的json字符串做处理
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //4.根据opndid去查t_wxuser对象
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        //4.1.如果有 = 绑定了 = return true给前端，做免密登录（不用输入密码就可以登录）
        if(wxuser!=null && wxuser.getUserId()!=null){
            //通过userId查user对象
            User user = userMapper.loadById(wxuser.getUserId());
            if(user != null){
                //通过user对象的logininfoId查logininfo对象
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

                //登陆成功，Jwt操作
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);

                return AjaxResult.me().setResultObj(map);
            }
        }

        //4.2.如果没有= 没有绑定 = return false = 让前端去跳转到绑定页面
        // ?accessToken=xxxx&openId=yyy;
        String params = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //一：校验：空值校验 手机号码和验证码
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode) ){
            throw new BusinessException("信息不能为null");
        }

        //二：校验: 校验手机验证码是否过期  或 是否正确
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if(codeObj==null){
            throw new BusinessException("手机验证码过期");
        }
        if(!codeObj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }


        //三：第三个请求并且替换数据，然后发送
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        //四：处理json字符串 - 微信用户信息 - 将json字符串转换一个Wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        /*
        {
            "openid":"OPENID",
            "nickname":"NICKNAME",
            "sex":1,
            "province":"PROVINCE",
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "privilege":[
            "PRIVILEGE1",
            "PRIVILEGE2"
            ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
         */

        //五：绑定流程 - phone绑定
        //1.通过phone去查t_user
        User user = userMapper.loadByPhone(phone);
        //a.如果有，直接绑定 -  //用户最开始用手机注册了，后来又用微信扫码注册了
        if(user==null){
            //b.如果没有，应该通过phone创建一个User对象，下添加t_logininfo,在添加user对象
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.save(logininfo);//自增id
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);//自增id
        }
        //2.将user_id设置到Wxuser对象,保存到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        //3.免密登录，返回token和logininfo
        //通过user对象的logininfoId查logininfo对象
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        //登陆成功，Jwt操作
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(result);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(4);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String address = jsonObject.getString("country")
                +jsonObject.getString("province")+jsonObject.getString("city");
        wxuser.setAddress(address);
        return wxuser;
    }
}
